<?php

namespace app\api\controller;

use app\admin\model\Exam_res;
use app\common\controller\Api;
use think\Db;

/**
 * 试题,试卷接口
 */
class Exam extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 1;
        $this->model = new \app\admin\model\Exam_res;
    }  

     /**
     * 试卷提交
     * @ApiSummary  (如果是模拟测试就让status传1，)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/exam/get_score)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token") 
     * @ApiParams   (name="ichapterid", type="integer", required=true, description="章节唯一标识,测试时候请使用119936,用此字段去匹配对应的试题")
     * @ApiParams   (name="status", type="integer", required=false, description="模拟测试就传1，")
     * @ApiReturnParams   (name="res", type="array", required=true, description="返回该章节下的试题数组")
     * @ApiReturnParams   (name="is_true", type="integer", required=true, description="答对了返回1，否则返回0,未选择就返回3")
     * @ApiReturnParams   (name="count", type="integer", required=true, description="试题数量")
     * @ApiReturnParams   (name="rate", type="string", required=true, description="正确率")
     * @ApiReturnParams   (name="canswer", type="string", required=true, description="试题正确答案")
     * @ApiReturnParams   (name="self_answer", type="string", required=true, description="你提交的答案")
     * @ApiReturn   ({
         {
          "code": 1,
          "msg": "提交成功",
          "time": "1586618743",
          "data": {
            "rate": "50.00%",
            res就是试题的数组
            "res": [
              {
                "is_true": 3,
                "self_answer": ""
              },
              {
                "is_true": 1,
                "self_answer": "B"
              }
            ],
            "count": 2
          }
        }

        {
          "code": 0,
          "msg": "已经提交过了，请勿重新提交",
          "time": "1586618901",
          "data": null
        }
      })
     */
    public function get_score()
    {
        $params = $this->request->request();
        
        if(empty($params['ichapterid'])) $this->error('缺少章节id');
        $ichapterid = $params['ichapterid'];
        
        $is_getstatus = $params['status'];

        $is_getstatus?$where['status']=2:$where['status']=0;//判断是否是模拟测试

        $self = Db::name('exam_res')->where($where)->where(['user_id'=>$this->user_id,'ichapterid'=>$ichapterid])->find();
        $self_answer = json_decode($self['answer'],true);
        if(empty($self_answer))$this->error('还未做过题目，无法提交');

        $exam_list = Db::name('exam')->field('id')->where(['ichapterid'=>$ichapterid])->select();//所有题目
        if(empty($exam_list))$this->error('该章节没有题目哦');

        //返回所有试题的情况
        foreach ($exam_list as $key => $value) {
            if(!empty(array_key_exists($value['id'], $self_answer))){
                $res[$key]['tihao'] = $key+1;
                $res[$key]['is_true'] = $self_answer[$value['id']]['is_true']; 
                $res[$key]['self_answer'] = $self_answer[$value['id']]['self_answer'];
            }else{
                $res[$key]['tihao'] = $key+1;
                $res[$key]['is_true'] = 3;
                $res[$key]['self_answer'] = '';
            }
        }

        $count = count($exam_list);//总题量
        $rate = $self['right']/$count*100;
        $rate = sprintf("%.2f",$rate). '%';

        // 判断该章节的分类是否是每日一练，是就添加数据
        $chapter_data = Db::name('chapter')->where(['ichapterid'=>$ichapterid])->field('category_id,id,clock,clock_user')->find();
        if($chapter_data['category_id']==14){

            $update_chapter['clock'] = $chapter_data['clock'] + 1;
            $update_chapter['clock_user'] = $chapter_data['clock_user'].$this->user_id.',';

            Db::name('chapter')->where(['id'=>$chapter_data['id']])->update($update_chapter);
        }

        $data['rate'] = $rate;
        $data['res'] = $res;
        $data['count'] = $count;

        $this->success('提交成功',$data);
    }

    /**
     * 单个试题提交
     * @ApiSummary  (请注意多选题有可能有E选项，如果是模拟测试就让status传1，)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/exam/onsubmit)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token") 
     * @ApiParams   (name="id", type="integer", required=true, description="试题唯一id")
     * @ApiParams   (name="status", type="integer", required=false, description="模拟测试就传个1，")
     * @ApiParams   (name="answer", type="string", required=true, description="用户提交的答案 判断题时候：提交'对'或者'错',选择题时候就直接传答案(记得要大写哦)如：ABC")
     * @ApiParams   (name="ichapterid", type="integer", required=true, description="章节唯一标识,用此字段去匹配对应的试题")
     * @ApiReturnParams   (name="dchangedate", type="string", required=true, description="试题修改发布时间")
     * @ApiReturnParams   (name="is_true", type="integer", required=true, description="答对了返回一，否则返回0")
     * @ApiReturnParams   (name="cdescription", type="string", required=true, description="试题解析")
     * @ApiReturnParams   (name="true_answer", type="string", required=true, description="试题正确答案")
     * @ApiReturnParams   (name="self_answer", type="string", required=true, description="你提交的答案")
     * @ApiReturn   ({
        {
          "code": 1,
          "msg": "回答错误",
          "time": "1586619254",
          "data": {
            "self_answer": "AB",
            "true_answer": "B",
            "cdescription": "123",
            "is_true": 0,
            "dchangedate": "2020-04-06 11:52:53"
          }
        }
        {
          "code": 1,
          "msg": "回答正确",
          "time": "1586619347",
          "data": {
            "self_answer": "对",
            "true_answer": "对",
            "cdescription": "12",
            "is_true": 1,
            "dchangedate": "2020-04-06 11:52:19"
          }
        }
        {
          "code": 0,
          "msg": "请勿重新提交",
          "time": "1586619278",
          "data": null
        }
     })
     */
    public function onsubmit(){

        $params = $this->request->request();
        if(empty($params['id'])) $this->error('缺少试题id');
        if(empty($params['ichapterid'])) $this->error('缺少ichapterid');
        if(empty($params['answer'])) $this->error('缺少answer:用户提交的答案');
        $code = Db::name('code')->where(['user_id'=>$this->user_id])->field('category_id')->select();
        
        $code_pass = 0;
        foreach ($code as $key => $value) {
          $chapter_id_list = Db::name('chapter')->where(['category_id'=>$value['category_id']])->column('ichapterid');
          if(in_array($params['ichapterid'], $chapter_id_list)){
            $code_pass = 1;
          }
        }
        if($code_pass==0){
          $experience_num = Db::name('user')->where(['id'=>$this->user_id])->value('experience_num');
          if($experience_num<=0)$this->error('体验次数用完请联系客服');
        }
        if($code_pass==0){
          $experience_num = Db::name('user')->where(['id'=>$this->user_id])->value('experience_num');
          if($experience_num<=0)$this->error('体验次数用完请联系客服');
        }

        $is_getstatus = $params['status'];
        $is_getstatus?$where['status']=2:$where['status']=0;//判断是否是模拟测试

        $self_res = Db::name('exam_res')
            ->where($where)
            ->where(['ichapterid'=>$params['ichapterid']])
            ->where(['user_id'=>$this->user_id])->find();

        $now_subject = Db::name('exam')->where(['id'=>$params['id'],'ichapterid'=>$params['ichapterid']])->find();//试题详细内容

        if(empty($now_subject))$this->error('试题id和章节id不对应');

        $now_subject['canswer']==$params['answer']?$is_true = 1:$is_true = 0;//判断答案是否正确

        $data = [];//返回给用户的提示 
        $data['self_answer']=$params['answer'];
        $data['true_answer']=$now_subject['canswer'];
        $data['cdescription']=$now_subject['cdescription'];
        $data['is_true']=$is_true;
        $data['dchangedate']=empty($now_subject['dchangedate'])?'暂无':$now_subject['dchangedate'];

        $insert_params = [];//到时候修改为json数据
        $insert_params['user_id'] = $this->user_id;
        $insert_params['ichapterid'] = $params['ichapterid'];

        $answer[$params['id']]['is_true'] = $is_true;
        $answer[$params['id']]['self_answer'] = $params['answer'];//用户提交的答案

        $insert_params['answer'] = json_encode($answer);//当前的试题的json数据

        // 之前没打过题
        if(empty($self_res)){
            if($is_true)$insert_params['right'] = 1;//答对就为1
            if($is_getstatus)$insert_params['status']=2;//判断是否是模拟测试
            $res = $this->model->isUpdate(false)->save($insert_params);
        }else{
            $pass_answer = json_decode($self_res['answer'],true);//之前提交的答案json

            $insert_params['id'] = $self_res['id']; 

            // 同一道题目
            if(array_key_exists($params['id'], $pass_answer)){
                $pass_true = $pass_answer[$params['id']]['is_true'];

                // 如果以前打错了，现在答对了就加正确率
                if($is_true&&!$pass_true){
                    //正确题目数量
                    $pass_right = $self_res['right'];
                    $insert_params['right'] = $pass_right + 1;

                // 之前答对现在打错
                }else if(!$is_true&&$pass_true){
                  $pass_right = $self_res['right'];
                    $insert_params['right'] = $pass_right - 1;
                }

                $pass_answer[$params['id']]['is_true'] = $is_true;
                $pass_answer[$params['id']]['self_answer'] = $params['answer'];

                $insert_params['answer'] = json_encode($pass_answer);

                $res = $this->model->isUpdate(true)->save($insert_params);
                // $this->error('请勿重新提交');

            } else{
                // 没打过题的可以做加正确率
                if($is_true){
                    //正确题目数量
                    $pass_right = $self_res['right'];
                    $insert_params['right'] = $pass_right + 1;
                }
                $now_insert = $answer + $pass_answer;

                $insert_params['answer'] = json_encode($now_insert);

                $res = $this->model->isUpdate(true)->save($insert_params);
            }
        }
        
        Db::name('user')->where(['id'=>$this->user_id])->setDec('experience_num',1);

        if($res) $this->success($is_true?'回答正确':'回答错误',$data);
    }

     /**
     * 获取试题内容
     * @ApiSummary  (请注意多项选题有可能有E选项，如果是模拟测试就让status传1，)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/exam/get_exam)
     * @ApiParams   (name="ichapterid", type="integer", required=true, description="章节唯一标识,测试时候请使用119936,用此字段去匹配对应的试题")
     * @ApiParams   (name="status", type="integer", required=false, description="模拟测试就传1过来，")
     * @ApiReturnParams   (name="csubjecttype", type="integer", required=true, description="题目类型，1：判断题,2：单项选择题,3：多选题")
     * @ApiReturnParams   (name="canswer", type="string", required=true, description="试题正确答案")
     * @ApiReturnParams   (name="trueorfalse", type="integer", required=true, description="如果是判断题，答案是对是值为1，否则为0")
     * @ApiReturnParams   (name="ctitle", type="string", required=true, description="试题标题")
     * @ApiReturnParams   (name="cdescription", type="string", required=true, description="试题答案解析")
     * @ApiReturnParams   (name="is_true", type="int", required=true, description="如果该题目有提交过，就返回。1是答对过，0是答错了")
     * @ApiReturnParams   (name="self_answer", type="string", required=true, description="如果该题目有提交过，就会有返回。过往提交的答案")
     * @ApiReturn   ({
         'code':'1',
         'msg':'试题内容',
         'data':{
                "exam_data": [
                  {
                    "id": 110,
                    "ctitle": "测试手动判断题",
                    "csubjecttype": "1",
                    "canswer": "对",
                    "iscore": 123,
                    "cdescription": "测试手动判断题",
                    "A": null,
                    "B": null,
                    "C": null,
                    "D": null,
                    "E": null,
                    "ichapterid": "119936",
                    "trueorfalse": 0,
                    "dchangedate": null,
                    "updatetime": 1585909892,
                    "createtime": 1585909892
                  },
                  {
                    "id": 108,
                    "ctitle": "2020年2月1日某企业购入原材料一批，开出一张面值为113 000元，期限为3个月的商业承兑汇票。2020年5月1日该企业无力支付票款时，下列会计处理正确的是（　）。",
                    "csubjecttype": "3",
                    "canswer": "C",
                    "iscore": 1.5,
                    "cdescription": "商业承兑汇票到期企业无力兑付时应转为“应付账款”；银行承兑汇票到期企业不能兑付时应转为“短期借款”。故答案选C。",
                    "A": "A.借：应付票据 113 000 　　　贷：短期借款 113 000 \r\n",
                    "B": "B.借：应付票据 113 000 　　　贷：其他应付款 113 000 \r\n",
                    "C": "C.借：应付票据 113 000 　　　贷：应付账款 113 000 \r\n",
                    "D": "D.借：应付票据 113 000 　　　贷：预付账款 113 000 ",
                    "E": null,
                    "ichapterid": "119936",
                    "trueorfalse": null,
                    "dchangedate": null,
                    "updatetime": 1585809399,
                    "createtime": 1585809399
                  },
                  {
                    "id": 101,
                    "ctitle": "下列关于应付账款的处理中，正确的有（　）。",
                    "csubjecttype": "3",
                    "canswer": "ABD",
                    "iscore": 2,
                    "cdescription": "应付账款一般按确认时的应付金额入账，不考虑时间价值问题，不按到期应付金额的现值入账。",
                    "A": "A.货物与发票账单同时到达，待货物验收入库后，按发票账单登记入账 \r\n",
                    "B": "B.货物已到，但至月末时发票账单还未到达，应在月份终了时暂估入账 \r\n",
                    "C": "C.应付账款一般按到期时应付金额的现值入账 \r\n",
                    "D": "D.企业采购业务中形成的应付账款，在确认其入账价值时不需要考虑将要发生的现金折扣 ",
                    "E": null,
                    "ichapterid": "119936",
                    "trueorfalse": null,
                    "dchangedate": null,
                    "updatetime": 1585809399,
                    "createtime": 1585809399
                  },
         }
        })
     */
    public function get_exam(){

        $params = $this->request->request();
        if (!$params['ichapterid']) $this->error('很抱歉，缺少ichapterid');

        $exam_data = DB::name('exam')->where(['ichapterid'=>$params['ichapterid']])->order('weigh desc')->select();

        $is_getstatus = array_key_exists('status', $params);
        $is_getstatus?$where['status']=2:$where='';//判断是否是模拟测试

        $self_answer = Db::name('exam_res')->where($where)->where(['ichapterid'=>$params['ichapterid'],'user_id'=>$this->user_id])->value('answer');
        $self_answer = json_decode($self_answer,true);
        // dump($self_answer);die; 
        // dump($exam_data);die; 
        
        foreach ($exam_data as $key => $value) {
          if($self_answer){
                if(array_key_exists($value['id'], $self_answer)){
                    $exam_data[$key]['self_answer'] = $self_answer[$value['id']]['self_answer'];
                    $exam_data[$key]['is_true'] = $self_answer[$value['id']]['is_true'];
                }
            }
            // 遍历选择题的选项
            if($value['csubjecttype']!=="1"){

              $json_array = [];
              $json_array[0]['label'] = 'A';
              $json_array[0]['content'] = $value['A'];
              $json_array[1]['label'] = 'B';
              $json_array[1]['content'] = $value['B'];
              $json_array[2]['label'] = 'C';
              $json_array[2]['content'] = $value['C'];
              $json_array[3]['label'] = 'D';
              $json_array[3]['content'] = $value['D'];

              // $exam_data[$key]['xuanxiang']['A'] = $value['A'];
              // $exam_data[$key]['xuanxiang']['B'] = $value['B'];
              // $exam_data[$key]['xuanxiang']['C'] = $value['C'];
              // $exam_data[$key]['xuanxiang']['D'] = $value['D'];

              if(!empty($value['E'])){
                //  $exam_data[$key]['xuanxiang']['E'] = $value['E'];
                $json_array[4]['label'] = 'E';
                $json_array[4]['content'] = $value['E'];
              }

              $exam_data[$key]['xuanxiang'] = ($json_array);
            }else{

                unset($exam_data[$key]['A']);
                unset($exam_data[$key]['B']);
                unset($exam_data[$key]['C']);
                unset($exam_data[$key]['D']);
                unset($exam_data[$key]['E']);

                $json_array[0]['label'] = '对';
                $json_array[0]['content'] = '';
                $json_array[1]['label'] = '错';
                $json_array[1]['content'] = '';
                $exam_data[$key]['xuanxiang'] = ($json_array);
            }

        }
        
        
        $data['exam_data'] = $exam_data;

        $this->success('试题内容',$data);
    }

    /**
     * 首页点击分类后的下级
     * @ApiSummary  (有三种可能的返回结果。如果还有下级则返回下级分类,如果没下级就显示章节名称,如果选择了每日一练，返回的是以日期格式为key键名的数组clock_data)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/exam/get_list)
     * @ApiParams   (name="id", type="integer", required=true, description="分类id")
     * @ApiParams   (name="page",type=string,required=false,description="分页")
     * @ApiReturnParams   (name="child", type="array", required=true, description="分类的下级列表")
     * @ApiReturnParams   (name="chapter_list", type="array", required=true, description="章节列表")
     * @ApiReturnParams   (name="ichapterid", type="integer", required=true, description="章节id,到时候用这个去匹配试题内容的")
     * @ApiReturnParams   (name="cchaptername", type="string", required=true, description="章节名称")
     * @ApiReturnParams   (name="clock", type="integer", required=falses, description="累计打卡人数（选择了每日一练才返回）")
     * @ApiReturnParams   (name="icount", type="integer", required=true, description="该章节总共题目数量")
     * @ApiReturnParams   (name="status", type="integer", required=false, description="是否打过卡，1为是，0为否（选择了每日一练才返回）")
     * @ApiReturn   ({
         'code':'1',
         'msg':'每日一练列表',
         'data':{
            "clock_data": {
              "2020-04-03": [
                {
                  "date": "2020-04-03",
                  "cchaptername": "每日一练一",
                  "clock": 4,
                  "icount": 5,
                  "ichapterid": 119977,
                  "clock_user": "1,1,1,1,",
                  "status": 0
                },
                {
                  "date": "2020-04-03",
                  "cchaptername": "每日一练二",
                  "clock": 0,
                  "icount": 2,
                  "ichapterid": 119978,
                  "clock_user": null,
                  "status": 0
                }
              ],
              "2020-04-02": [
                {
                  "date": "2020-04-02",
                  "cchaptername": "第四章 所有者权益",
                  "clock": 0,
                  "icount": 103,
                  "ichapterid": 122869,
                  "clock_user": null,
                  "status": 0
                },
                {
                  "date": "2020-04-02",
                  "cchaptername": "第三章 负债",
                  "clock": 0,
                  "icount": 103,
                  "ichapterid": 122870,
                  "clock_user": null,
                  "status": 0
                },
                ]
            }
            }
        'code':'1',
        'msg':'下级列表',
        "data": {
            "child": {
              "total": 1,
              "per_page": 10,
              "current_page": 1,
              "last_page": 1,
              "data": [
                {
                  "id": 16,
                  "name": "初级会计职称",
                  "image": ""
                }
              ]
            }
          }

        'code':'1',
        'msg':'章节列表',
        "data": {
         "chapter_list": {
              "total": 60,
              "per_page": 10,
              "current_page": 1,
              "last_page": 6,
              "data": [
                {
                  "cchaptername": "第二节修改  应付及预收款项",
                  "ichapterid": 119936
                },
                {
                  "cchaptername": "2020真题模拟试卷二",
                  "ichapterid": 129682
                },
                
                {
                  "cchaptername": "第四节 会计科目和借贷记账法",
                  "ichapterid": 122873
                },
                {
                  "cchaptername": "第三节 会计要素及其确认与计量",
                  "ichapterid": 122872
                }
      ]
    }
        })
     */
    public function get_list()
    {
        $id = $this->request->request('id');
        $page = $this->request->request('page');

        if (!$id) $this->error('很抱歉，缺少分类id');

        // id == 14 是每日一练 就返回打卡记录,而且数据是根据时间进行分组的
        if($id == 14){
            
            $clock_data = Db::name('chapter')->field('FROM_UNIXTIME(updatetime,"%Y-%m-%d")as date, cchaptername,clock,icount,ichapterid,clock_user')->order('date DESC')->select();
            // $clock_data = $clock_data->items();//使用分页后要进行items才能处理数据
            $res = array();

            foreach ($clock_data as $key => $value) {

                $clock_user = array_filter(explode(',', $value['clock_user']));
                in_array($this->user_id, $clock_user)?$if_exist=1:$if_exist=0;
                
                $if_exist?$status = 1:$status = 0;
                $value['status'] = $status;

                $res[$value['date']][] = $value;
            }

            $data['clock_data']['data'] = $res;
            $this->success('每日一练列表',$data);
        }

        $count = Db::name('category')->where('pid','=',$id)->count();
        if(!empty($count)){
            $if_exist_child = Db::name('category')->field('id,name,image')->where('pid','=',$id)->order('weigh desc')->select();
        }

        // 为空就查章节出来
        if(empty($if_exist_child)){
            $chapter_list = Db::name('chapter')->field('cchaptername,ichapterid')->where(['category_id'=>$id])->order('weigh desc')->select();
            
            $data['chapter_list']['data'] = $chapter_list;
            $this->success('章节列表',$data); 
        }else{
          $data['child']['data'] = $if_exist_child;
          $this->success('下级列表',$data); 
        }
    }




}
